package com.imooc.animation360.view;

import com.imooc.animation360.R;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.BitmapFactory.Options;
import android.graphics.Paint.FontMetrics;
import android.util.AttributeSet;
import android.view.View;

public class FloatCircleView extends View {
	public int width = 150;
	public int height = 150;
	private Paint circlePaint;
	private Paint textPaint;
	private String text = "50%";
	public boolean isDraging = false;
	private Bitmap dest;
	
	public FloatCircleView(Context context) {
		this(context,null);
	}

	public FloatCircleView(Context context, AttributeSet attrs) {
		this(context, attrs,0);
	}

	public FloatCircleView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		initPaints();
		initBitmap();
	}

	private void initPaints() {
		circlePaint = new Paint();
		circlePaint.setColor(Color.GRAY);
		circlePaint.setAntiAlias(true);
		
		textPaint = new Paint();
		textPaint.setColor(Color.WHITE);
		textPaint.setTextSize(25);
		textPaint.setAntiAlias(true);
		textPaint.setFakeBoldText(true); //文字加粗.
	}
	
	private void initBitmap() {
		Bitmap src = BitmapFactory.decodeResource(getResources(), R.drawable.cartoon);
		dest = Bitmap.createScaledBitmap(src, width, height, true);
	}


	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		setMeasuredDimension(width, height);
		
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		//绘制图片.
		if(isDraging){
			canvas.drawBitmap(dest, 0, 0, null); //绘制文本和圆圈需要画笔,绘制图片可以不需要.
		}else{
			//绘制圆圈.
			canvas.drawCircle(width/2, height/2, width/2, circlePaint);
			
			//绘制文本.
			float textWidth = textPaint.measureText(text);  //获取文本内容的宽度.
			float x = width/2-textWidth/2;
			FontMetrics fontMetrics = textPaint.getFontMetrics();  //获取字体的规格.
			//获取字体的偏移量,由于y坐标是字体底部的基线坐标,而不是字体的中心 ,但是我们需要的是字体的中线与圆的中线对齐,因此需要将字体适当往下平移,
			//平移的量应该是基线上方的距离|ascent|减去基线下方的descent的结果除以2.相当于将多余的距离平分.由于ascent是负值,descent正值,
			//所以按下面写即可:
			float dy = -(fontMetrics.ascent+fontMetrics.descent)/2; 
			float y = height/2+dy;
			canvas.drawText(text, x, y, textPaint);
		}
	}
	
	/**
	 * 设置拖拽状态的方法.
	 * 总共只有种状态,拖拽时的状态和没有拖拽的状态.
	 * @param b
	 */
	public void setDragState(boolean b){
		isDraging = b;
		invalidate();
	}
}
